package org.example.redisdemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 1. Key 和 HashKey 统一用 StringRedisSerializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        // 2. 配置 JSON 序列化器
        ObjectMapper objectMapper = new ObjectMapper();
        PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
                .allowIfSubType(Object.class)
                .build();
        objectMapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());

        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);

        // 3. Value 序列化：String 类型的值用 StringRedisSerializer，其他用 JSON
        template.setValueSerializer(new RedisSerializer<>() {
            private final StringRedisSerializer stringSerializer = new StringRedisSerializer();

            @Override
            public byte[] serialize(Object o) {
                if (o instanceof String) {
                    return stringSerializer.serialize((String) o);
                }
                return jsonRedisSerializer.serialize(o);
            }

            @Override
            public Object deserialize(byte[] bytes) {
                if (bytes == null) return null;
                String str = stringSerializer.deserialize(bytes);
                return (str != null && str.startsWith("\"") && str.endsWith("\"")) ? jsonRedisSerializer.deserialize(bytes) : str;
            }
        });

        // 4. Hash Value 也做类似处理，避免 String 额外的 `\"`
        template.setHashValueSerializer(new RedisSerializer<>() {
            private final StringRedisSerializer stringSerializer = new StringRedisSerializer();

            @Override
            public byte[] serialize(Object o) {
                if (o instanceof String) {
                    return stringSerializer.serialize((String) o);
                }
                return jsonRedisSerializer.serialize(o);
            }

            @Override
            public Object deserialize(byte[] bytes) {
                if (bytes == null) return null;
                String str = stringSerializer.deserialize(bytes);
                return (str != null && str.startsWith("\"") && str.endsWith("\"")) ? jsonRedisSerializer.deserialize(bytes) : str;
            }
        });

        template.afterPropertiesSet();
        return template;
    }
}
